<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="ios-thunderstorm"></Icon>
      应用集群管理
    </p>
    <a href="#" v-if="permission.namespace_create === '1'" slot="extra" @click.prevent="createModal=true">
      <Icon type="md-add-circle"></Icon>
      创建
    </a>
    <Modal v-model="createModal" draggable scrollable title="新建应用集群" :footer-hide=true>
      <Form ref="formCreate" :model="formCreate" :rules="ruleCreate" :label-width="80">
        <FormItem label="名称" prop="namespace_name">
          <Input v-model="formCreate.namespace_name" placeholder="输入命名空间名称"></Input>
        </FormItem>
        <FormItem label="云平台" prop="cloud_name">
          <Select v-model="formCreate.cloud_name">
            <Option v-for="item in cloud_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="success" @click="createNamespace('formCreate')" style="margin-left: 50px">点击提交</Button>
          <Button type="warning" @click="handleReset('formCreate')" style="margin-left: 10px">清空</Button>
          <Button type="info" @click="closeView('formCreate')" style="margin-left: 10px">关闭</Button>
        </FormItem>
      </Form>
    </Modal>
    <div style="padding-bottom: 10px;">
      <Row :gutter="16">
        <Col span="6">
          <Select v-model="cloud_name"  placeholder="请选择云平台" @on-change="GetCloudNamespaces">
            <Option v-for="item in cloud_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
      </Row>
    </div>
    <Table border :loading="loading" :columns="columns" :data="data">
      <template slot-scope="{ row, index }" slot="index">
        <span>{{index+1}}</span>
      </template>
      <template slot-scope="{ row, index }" slot="status">
        <span v-if="`${row.status}`=='Terminating'" style="color:#ed4014">正在删除...</span>
        <span v-else style="color:#19be6b">正在运行</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <Button v-if="permission.namespace_delete === '1'" type="error" size="small" @click="remove(index)">删除</Button>
        <span v-else style="color:#ed4014">无权限</span>
      </template>
    </Table>
  </Card>
</template>

<script>
import { addNamespace, namespaceList, deleteNamespace } from '@/api/production'

  export default {
    data () {
      return {
        loading: false,
        createModal: false,
        formCreate: {
          cloud_name: '',
          namespace_name: ''
        },
        ruleCreate: {
          cloud_name: [{ required: true, message: '云平台名称', trigger: 'blur' }],
          namespace_name: [{ required: true, message: '命名空间名称', trigger: 'blur' }]
        },
        columns: [
          {
            title: '序号',
            slot: 'index',
            width: '150',
            align: 'center'
          },
          {
            title: '命名空间名称',
            key: 'name'
          },
          {
            title: '所属集群',
            key: 'cluster'
          },
          {
            title: '运行状态',
            key: 'status',
            slot: 'status'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 200,
            align: 'center'
          }
        ],
        data: [],
        permission: '',
        cloud_name: '',
        cloud_list: [
          {value: 'aliyun', label: '阿里云'},
          // {value: 'aws-stg', label: 'AWS-STG'},
          // {value: 'aws-prod', label: 'AWS-PROD'}
        ]
      }
    },
    methods: {
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      },
      GetCloudNamespaces (CronStatus) {
        if (this.cloud_name.length !== 0 ) {
          if (CronStatus === true) {
            this.loading = false;
          } else {
            this.loading = true;
          }
          this.data_list({'cloud_name': this.cloud_name})
        }
      },
      // 获取所有命名空间
      data_list (cloud) {
        namespaceList(cloud).then(res => {
          this.loading = false;
          this.data = res.data.results
        });
      },
      closeView (name) {
        this.createModal = false;
        this.handleReset(name);
      },
      createNamespace (name) {
        // 请求后端接口创建数据
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口创建数据
            addNamespace(this.formCreate).then(res => {
              this.GetCloudNamespaces()  //在创建新地址时再次请求数据
              this.$Message.success({content:'创建成功!',duration: 5,closable: true});
            }).catch( err => {
              this.$Message.error({content:'创建失败!',duration: 5,closable: true})
            })
          }
        })
      },
      // 清空表单
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      // 删除
      remove (index) {
        this.$Modal.confirm({
          title: "警告!",
          content: `<p>删除${this.data[index].name}后会导致该环境下所有关联应用全部删除，是否继续？</p>`,
          onOk: () => {
            var params = {
              'cloud_name': this.cloud_name,
              'namespace_name': this.data[index].name
            }
            deleteNamespace(params).then(res => {
              // this.data_list()
              this.GetCloudNamespaces()
              this.$Message.success({content:'删除成功!',duration: 5,closable: true})
            }).catch(err => {
              this.$Message.error({content:'删除失败!',duration: 5,closable: true})
            })
          },
          onCancel: () => {
            this.$Message.info('已取消删除');
          }
        })
      },
      // 定时获取数据并重新加载页面
      cronGetNamespace () {
        this.cronGet = setInterval(() => this.GetCloudNamespaces(true), 20000)
      }
    },
    created () {
      this.get_permission();
      this.cronGetNamespace();
    },
    beforeDestroy () {
      // 退出当前页面时清除此定时请求任务
      clearInterval(this.cronGet)
    }
  }
</script>